// 同步版本
export const funcSync = (func, args, errCb) => {
  return new Promise((resolve, reject) => {
    try {
      if (!func) {
        resolve({ error: '必须传入一个api' })
      }
      func({
        ...args,
        complete: (res) => {
          resolve(res)
        }
      })
    } catch(err) {
      if (errCb) {
        errCb()
      }
      reject(err)
    }
  })
}
// nextTick同步
export const nextTick = (self) => {
  return new Promise((resolve, reject) => {
    try {
      self.$nextTick(() => {
        resolve()
      })
    } catch(err) {
      reject(err)
    }
  })
}
// 防抖
export function debounce(func, wait, immediate) {
  let timeout, result
  let debounced = function () {
    let context = this
    let args = arguments
    if (timeout) clearTimeout(timeout)
    if (immediate) {
      // 如果已经执行过，不再执行
      let callNow = !timeout
      timeout = setTimeout(function(){
        timeout = null
      }, wait)
      if (callNow) result = func.apply(context, args)
    }
    else {
      timeout = setTimeout(function(){
        func.apply(context, args)
      }, wait)
    }
    return result
  }
  debounced.cancel = function() {
    clearTimeout(timeout)
    timeout = null
  }
  return debounced
}
// rpx转px
export const rpxTopx = rpx => {
  const { windowWidth } = uni.getSystemInfoSync()
  return rpx / 750 * windowWidth
}
// px转rpx
export const pxTorpx = px => {
  const { windowWidth } = uni.getSystemInfoSync()
  return px * 750 / windowWidth
}
